<!--
  @Description:楼层商品明细
  @Author:zqy
  @Date:2022-12-16 10:37:27
  @Last Modified by:zqy
  @Last Modified time:2022-12-16 10:37:27
-->
<template>
  <div>
    <div slot="table-before" class="qup-title-box item-title">
      <div><span class="border" /><span>商品明细</span></div>
      <div class="alert-msg"><span v-if="layoutData.maxCount>0">最多新增{{ layoutData.maxCount }}条{{ layoutData.type | filterLayoutType }}数据，</span>按序号排序进行显示。</div>
    </div>
    <table-box
      ref="refTable"
      :selected-arry.sync="tableSelected"
      :table-config="tableConfig"
      :other-filters="otherFilters"
      :table-height="400"
      table-row-key="id"
      :table-sortable="false"
      show-index
      show-selection
      :show-page="Number(layoutData.maxCount || 0)===0"
      :show-custom-setting="false"
      :show-custom-combine="false"
      :show-custom-collect="false"
      @data-change="dataChange"
      @row-dblclick="dbClickRow"
      @selection-change="handleSelectionChange"
    >
      <div slot="combine-before">
        <template v-if="enbleStateChange">
          <el-button size="mini" type="primary" @click="handleUpDown(1)">上架</el-button>
          <el-button size="mini" type="primary" @click="handleUpDown(0)">下架</el-button>
          <el-button size="mini" type="primary" @click="handleAutoOffShelfConfig">自动下架配置</el-button>
        </template>
        <el-button v-if="enbleExport" size="mini" type="primary" @click="handleExport">导出</el-button>
        <el-button v-if="enbleImport" size="mini" type="primary" @click="handleImport">导入</el-button>
        <el-button v-if="enbleCreate" size="mini" type="primary" @click="handleEdit">添加</el-button>
        <el-button v-if="enbleDelete" size="mini" type="primary" @click="handleBatchDelete">删除</el-button>
      </div>
    </table-box>
    <CheckProductItem
      v-if="showEdit"
      ref="refEdit"
      :visible.sync="showEdit"
      :detail="activeRowData"
      :floor-id="floorId"
      @success="refreshTable"
    />
    <import-files
      v-if="importDlg.visible"
      title="导入商品"
      :visible.sync="importDlg.visible"
      :config="importDlg.config"
      :task-config="importDlg.taskConfig"
      @success="handleImportSuccess"
      @close="refreshTable(true)"
    />

    <!-- 导出 -->
    <export-files
      v-if="showExport"
      title="导出商品"
      :visible.sync="showExport"
      :config="exportConfig"
    />
    <!-- 自动下架配置 -->
    <ProductAutoStatusConfig
      v-if="showStatusConfig"
      :visible.sync="showStatusConfig"
      :floor-id="floorId"
    />
  </div>
</template>

<script>
import { FLOOR_TYPE } from '../constData'
import { queryBtnList } from '@/api/permissions'
import { delFloorDetail, delBatchFloorDetail, updateSort, updateProductUpDown } from '@/api/floorProductDetail'
import CheckProductItem from './CheckProductItem'
import ProductAutoStatusConfig from '../../ProductAutoStatusConfig'

export default {
  name: 'FloorItemList',
  filters: {
    filterLayoutType(val) {
      return FLOOR_TYPE[val] || ''
    }
  },
  components: { CheckProductItem, ProductAutoStatusConfig },
  props: {
    pageData: {
      type: Object,
      default: () => {}
    },
    floorId: {
      type: String,
      default: ''
    },
    layoutData: {
      type: [String, Object],
      default: ''
    } // 楼层布局
  },
  data() {
    const that = this
    return {
      showEdit: false,
      showStatusConfig: false,
      tableData: [],
      activeRowData: '', // 当前选中行数据
      tableSelected: [], // 当前所选中表格行数据
      otherFilters: [], // 表格额外查询条件
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/v2FloorProductDetail/page`,
        tabIndex: 20,
        buttonGroupCode: 'floorDetail',
        // hideFuncBar: true,
        onlySearchBar: true,
        pageFlag: true,
        sort: 'sort',
        order: 'asc',
        setting: [
          {
            prop: 'skuName',
            label: '商品名称',
            minWidth: 250
          },
          {
            prop: 'skuCode',
            label: '商品编码',
            minWidth: 150
          },
          {
            prop: 'status',
            label: '状态',
            minWidth: 80,
            type: 'select',
            /* formatData: ({ status }) => {
              return status === 'DOWN' ? '下架' : status === 'UP' ? '上架' : ''
            }, */
            propEnum: {
              list: [
                { dictCode: 'UP', dictName: '上架' },
                { dictCode: 'DOWN', dictName: '下架' }
              ]
            }
          },
          {
            prop: 'sort',
            label: '排序',
            width: 200,
            sortable: false,
            type: 'hidden',
            overflowHidden: false,
            render: (_h, row) => {
              const btns = []
              if (this.hasPermission('top')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'top')} class='btn-green my-txt-btn'>置顶</el-button>)
              }
              if (this.hasPermission('up')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'moveUp')} class='btn-green my-txt-btn'>上移</el-button>)
              }
              if (this.hasPermission('down')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'moveDown')} class='btn-green my-txt-btn'>下移</el-button>)
              }
              if (this.hasPermission('bottom')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'bottom')} class='btn-green my-txt-btn'>置底</el-button>)
              }
              return _h('div', btns)
            }
          },
          {
            prop: 'lastUpdateBy',
            label: '修改人',
            width: 100,
            type: 'hidden'
          },
          {
            prop: 'lastUpdateTime',
            label: '修改时间',
            width: 150,
            type: 'hidden'
          },
          {
            prop: 'opetate',
            label: '操作',
            width: 120,
            sortable: false,
            type: 'hidden',
            overflowHidden: false,
            render: (_h, row) => {
              const btns = []
              if (this.hasPermission('edit')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleEdit.bind(this, row)} class='btn-green my-txt-btn'>重新选择</el-button>)
              }
              if (this.hasPermission('del')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleDelete.bind(this, row)} class='btn-green my-txt-btn'>删除</el-button>)
              }
              return _h('div', btns)
            }
          }
        ],
        btnList: []
      },
      buttons: [],
      sorting: false,
      importDlg: { // 导入配置
        visible: false,
        config: [{
          name: '导入商品数据', // 任务名
          code: 'floorProductDetailImportTemp', // 模板编码（必填）
          async: true,
          apiUrl: `${process.env.VUE_APP_BASE_API}/api/v1/v2FloorProductDetail/import`,
          paramsRaw: {
            floorConfId: this.floorId // 楼层ID
            // menuCode: '', // 菜单编码 选填
          }
          /* bizParam: '' */
        }],
        taskConfig: {
          apiPrefix: process.env.VUE_APP_BASE_API,
          checkRowApi: `${process.env.VUE_APP_BASE_API}/api/v1/v2FloorProductDetail/checkRow`, // 行校验
          checkApi: `${process.env.VUE_APP_BASE_API}/api/v1/v2FloorProductDetail/check`, // 全局校验
          completeApi: `${process.env.VUE_APP_BASE_API}/api/v1/v2FloorProductDetail/execImport`, // 完成导入
          exportTempApi: `${process.env.VUE_APP_BASE_API}/api/v1/excel/tempData/export` // 临时数据导出
        }
      },
      showExport: false, // 是否导出
      exportConfig: [
        {
          code: 'product_export', // 导出编码，前段定义，同一个config中code不能重复
          name: '导出商品', // 导出名称，如：商品导出，导出用户
          async: false, // 是否异步
          templateCode: 'PRODUCT_EXPORT', // 模板code，若需要则由后端提供
          dataApi: `${process.env.VUE_APP_BASE_API}/api/v1/v2FloorProductDetail/export`, // 导出数据的接口地址
          templateApi: ``, // 模板导出接口
          templateMethod: 'post',
          filtersRaw: [], // filter查询参数
          paramsRaw: {}, // params查询参数
          selectedRows: [], // 当前所选中的数据行
          queryField: 'id'// 指定行导出的字段名称
        }
      ]
    }
  },

  computed: {
    enbleDelete() {
      return this.hasPermission('del')
    },
    enbleCreate() {
      if (!this.hasPermission('add')) {
        return false
      }
      if (this.tableData && this.layoutData && this.layoutData.maxCount > 0) {
        return this.tableData.length < this.layoutData.maxCount
      }
      return true
    },
    enbleImport() {
      return this.hasPermission('import')
    },
    enbleExport() {
      return this.hasPermission('export')
    },
    enbleStateChange() {
      // 因此界面权限，有增删权限就能上下架
      return this.hasPermission('add')
    }
  },

  created() {
    this.otherFilters = [
      { id: 'floorConfId', property: 'floorConfId', operator: '=', value: this.floorId }
    ]
    this.getBtnsList()
  },
  methods: {
    getBtnsList() {
      const menuCode = this.$route.query.menuCode
      if (!menuCode) return
      const buttonGroupCode = 'floorDetail'
      queryBtnList({ menuCode, buttonGroupCode }).then(res => {
        // res.data.groovyList
        this.buttons = (res.data && res.data.groovyList) || []
      })
    },
    hasPermission(code) {
      if (!this.isProduction) return true
      return this.buttons.filter(v => v.buttonCode === code).length > 0
    },
    dataChange(res) {
      this.tableData = (res && res.data && res.data.records) || []
    },
    handleSelectionChange(rows) {
      this.tableSelected = rows
    },
    dbClickRow(row, e) {
      this.tableSelected = [row]
    },
    // 刷新表格数据
    refreshTable(isInit) {
      this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
    },
    // 新增/编辑基础信息
    handleEdit(row) {
      if (row && row.id) {
        this.activeRowData = row
      } else {
        this.activeRowData = ''
      }
      this.$nextTick(() => {
        this.showEdit = true
      })
    },
    // 删除处理
    handleDelete(row) {
      this.$confirm('此操作将永久删除当前所选商品, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = row.id
        delFloorDetail(id).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '删除成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    handleBatchDelete() {
      if (this.tableSelected.length === 0) {
        this.$message.warning('请先选择需要删除的商品')
        return
      }
      this.$confirm('此操作将永久删除当前所选商品, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.tableSelected.map(v => v.id)
        delBatchFloorDetail(ids).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '删除成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    /**
     * 排序
     * @param {Object} row 排序行
     * @param {string} type 移动类型(bottom 置底 ，top 置顶 ， moveDown 下移 ，  moveUp 上移)
    */
    handleSort(row, type) {
      if (this.sorting) return
      const now = Date.now()
      if (this.sortTime) {
        const diffTime = Math.floor((now - this.sortTime) / 1000)
        // 对比排序操作时间差，大于2s的可操作
        if (diffTime < 2) return
      }
      this.sortTime = now
      const params = {
        id: row.id,
        type
      }
      this.sorting = true
      updateSort(params).then(res => {
        this.sorting = false
        if (res.success === 1) {
          this.refreshTable()
        }
      }).catch(() => {
        this.sorting = false
      })
    },
    // 导入
    handleImport() {
      this.importDlg.visible = true
    },
    // 导入成功
    handleImportSuccess(data) {
      this.importDlg.visible = false
      if (data && data.msg) {
        this.$confirm(`<div style="line-height:22px;font-size:12px">${data.msg}</div>`, '部分导入成功；存在以下异常：', {
          showCancelButton: false,
          showConfirmButton: false,
          type: 'warning',
          dangerouslyUseHTMLString: true
        })
      }
    },
    // 导出
    handleExport() {
      let filtersRaw = this.otherFilters
      const allFilters = this.$refs.refTable.getAllFilters()

      if (allFilters.searchBarFilter) {
        filtersRaw = [...filtersRaw, ...allFilters.searchBarFilter]
      }
      if (allFilters.combineFilter) {
        filtersRaw = [...filtersRaw, ...allFilters.combineFilter]
      }
      const exportConfig = this.exportConfig[0]
      exportConfig.filtersRaw = filtersRaw
      exportConfig.selectedRows = this.tableSelected || []
      this.$set(this.exportConfig, 0, exportConfig)
      this.$nextTick(() => {
        this.showExport = true
      })
    },
    /**
     * 上下架
     * @param {Number} status  上下架：1 上架，0 下架
     * */
    handleUpDown(status) {
      const statusName = status === 1 ? '上架' : '下架'
      if (this.tableSelected.length === 0) {
        this.$message.warning(`请先选择需要${statusName}的商品`)
        return
      }
      this.$confirm(`此操作将设置当前所选商品为“${statusName}”状态, 是否继续? `, `${statusName}提示`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.tableSelected.map(v => v.id)
        updateProductUpDown(status, ids).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || `${statusName}成功`,
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    // 自动下架配置
    handleAutoOffShelfConfig() {
      this.showStatusConfig = true
    }
  }
}

</script>
<style lang='scss' scoped>
  .item-title{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .alert-msg{
      flex: 1;
      font-size: 12px;
      color: #999;
      margin-left: 20px;
      font-weight: normal;
    }
  }
  .my-txt-btn{
    padding: 0 !important;
  }

 .cover-image{
    padding: 5px 0;
    line-height: 0;
    font-size: 0;
    img{
      max-height: 70px;
      max-width: 100px;
      object-fit: cover;
    }
  }
</style>
